<template>
  <div class="ai-chat-container">
    <!-- 侧边栏 -->
    <aside class="sidebar" :class="{ collapsed: sidebarCollapsed }">
      <div class="sidebar-header">
        <button @click="toggleSidebar" class="sidebar-toggle">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <path d="M3 12h18m-9-9l9 9-9 9"/>
          </svg>
        </button>
        <h2 v-if="!sidebarCollapsed" class="sidebar-title">AI文本助手</h2>
      </div>

      <div v-if="!sidebarCollapsed" class="sidebar-content">
        <button @click="createNewChat" class="new-chat-btn">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <path d="M12 5v14m-7-7h14"/>
          </svg>
          新建对话
        </button>

        <!-- 功能选择 -->
        <div class="module-selector">
          <select v-model="selectedModule" @change="onModuleChange" class="module-select">
            <option value="creative">💡 智能写作</option>
            <option value="academic">📚 学术写作</option>
          </select>
        </div>

        <!-- 搜索框 -->
        <div class="search-container">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" class="search-icon">
            <circle cx="11" cy="11" r="8"/>
            <path d="m21 21-4.35-4.35"/>
          </svg>
          <input 
            type="text" 
            v-model="searchQuery" 
            placeholder="搜索对话..." 
            class="search-input"
            @input="filterRecords"
          />
        </div>

        <!-- 对话历史 -->
        <div class="chat-history">
          <div class="history-header">
            <span class="history-title">对话历史</span>
            <button @click="toggleSortOrder" class="sort-btn">
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <path d="M3 6h18M7 12h10m-7 6h4"/>
              </svg>
            </button>
          </div>
          
          <div class="history-list">
            <div
              v-for="record in displayedRecords"
              :key="record.id"
              :class="['history-item', { active: record.id === currentRecordId }]"
              @click="loadRecord(record.id)"
            >
              <div class="history-content">
                <div class="history-title">{{ truncateText(record.prompt, 35) }}</div>
                <div class="history-time">{{ formatRelativeTime(record.created_at) }}</div>
              </div>
              <div class="history-actions">
                <button @click.stop="toggleFavorite(record)" class="action-btn" :class="{ favorited: record.is_favorite }">
                  <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <polygon points="12,2 15.09,8.26 22,9.27 17,14.14 18.18,21.02 12,17.77 5.82,21.02 7,14.14 2,9.27 8.91,8.26"/>
                  </svg>
                </button>
                <button @click.stop="deleteRecord(record.id)" class="action-btn delete-btn">
                  <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <path d="M3 6h18M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/>
                  </svg>
                </button>
              </div>
            </div>
            
            <div v-if="displayedRecords.length === 0" class="empty-state">
              <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
                <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>
              </svg>
              <p>暂无对话记录</p>
            </div>
          </div>
        </div>
      </div>
    </aside>

    <!-- 主对话区域 -->
    <main class="main-content">
      <!-- 对话区域 -->
      <div class="chat-area" ref="chatArea">
        <!-- 欢迎界面 -->
        <div v-if="!currentRecordId && !generatedResult && !generating && recordList.length === 0" class="welcome-screen">
          <div class="welcome-content">
            <div class="ai-avatar">
              <svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
                <path d="M12 2L2 7l10 5 10-5-10-5z"/>
                <path d="M2 17l10 5 10-5"/>
                <path d="M2 12l10 5 10-5"/>
              </svg>
            </div>
            <h1 class="welcome-title">AI文本助手</h1>
            <p class="welcome-subtitle">{{ getModuleText(selectedModule) }}</p>
            
            <div class="feature-grid">
              <div class="feature-card">
                <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                  <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
                  <polyline points="14,2 14,8 20,8"/>
                </svg>
                <span>智能写作</span>
              </div>
              <div class="feature-card">
                <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                  <path d="M9 11H5a2 2 0 0 0-2 2v3a2 2 0 0 0 2 2h4l3 3V8l-3 3z"/>
                </svg>
                <span>多种风格</span>
              </div>
              <div class="feature-card">
                <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                  <polyline points="22,12 18,12 15,21 9,3 6,12 2,12"/>
                </svg>
                <span>高质量输出</span>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 对话消息 -->
        <div v-else class="messages-container" ref="messagesContainer">
          <!-- 历史对话 -->
          <div v-if="currentRecordId && currentRecord && !generatedResult" class="message-group">
            <div class="message user-message">
              <div class="message-avatar user-avatar">
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                  <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/>
                  <circle cx="12" cy="7" r="4"/>
                </svg>
              </div>
              <div class="message-content">
                <div class="message-text">{{ currentRecord.prompt }}</div>
                <div class="message-time">{{ formatRelativeTime(currentRecord.created_at) }}</div>
              </div>
            </div>
            
            <div class="message ai-message">
              <div class="message-avatar ai-avatar">
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                  <path d="M12 2L2 7l10 5 10-5-10-5z"/>
                  <path d="M2 17l10 5 10-5"/>
                  <path d="M2 12l10 5 10-5"/>
                </svg>
              </div>
              <div class="message-content">
                <div class="message-text">{{ currentRecord.generated_content }}</div>
                <div class="message-actions">
                  <button @click="copyText(currentRecord.generated_content)" class="action-btn">
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                      <rect x="9" y="9" width="13" height="13" rx="2" ry="2"/>
                      <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>
                    </svg>
                    复制
                  </button>
                </div>
              </div>
            </div>
          </div>

          <!-- 当前生成的对话 -->
          <div v-if="generatedResult" class="message-group">
            <div class="message user-message">
              <div class="message-avatar user-avatar">
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                  <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/>
                  <circle cx="12" cy="7" r="4"/>
                </svg>
              </div>
              <div class="message-content">
                <div class="message-text">{{ generateForm.prompt }}</div>
                <div class="message-time">刚刚</div>
              </div>
            </div>
            
            <div class="message ai-message">
              <div class="message-avatar ai-avatar">
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                  <path d="M12 2L2 7l10 5 10-5-10-5z"/>
                  <path d="M2 17l10 5 10-5"/>
                  <path d="M2 12l10 5 10-5"/>
                </svg>
              </div>
              <div class="message-content">
                <div class="message-text">{{ generatedResult.generated_content }}</div>
                <div class="message-actions">
                  <button @click="copyText(generatedResult.generated_content)" class="action-btn">
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                      <rect x="9" y="9" width="13" height="13" rx="2" ry="2"/>
                      <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>
                    </svg>
                    复制
                  </button>
                </div>
              </div>
            </div>
          </div>

          <!-- 生成中状态 -->
          <div v-if="generating" class="message ai-message generating">
            <div class="message-avatar ai-avatar">
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <path d="M12 2L2 7l10 5 10-5-10-5z"/>
                <path d="M2 17l10 5 10-5"/>
                <path d="M2 12l10 5 10-5"/>
              </svg>
            </div>
            <div class="message-content">
              <div class="typing-indicator">
                <span></span>
                <span></span>
                <span></span>
              </div>
            </div>
          </div>
        </div>

      </div>

      <!-- 输入区域 -->
      <div class="input-area">
        <!-- 设置面板 -->
        <div class="settings-panel" :class="{ expanded: showSettings }">
          <div class="settings-grid">
            <div class="setting-item">
              <label>内容类型</label>
              <select v-model="generateForm.content_type" @change="onContentTypeChange">
                <option v-for="option in contentTypeOptions" :key="option.value" :value="option.value">
                  {{ option.label }}
                </option>
              </select>
            </div>
            <div class="setting-item">
              <label>语言风格</label>
              <select v-model="generateForm.language_style" @change="onLanguageStyleChange">
                <option value="casual">随意</option>
                <option value="formal">正式</option>
                <option value="professional">专业</option>
                <option value="creative">创意</option>
                <option value="academic">学术</option>
                <option value="poetic">诗意</option>
                <option value="humorous">幽默</option>
                <option value="serious">严肃</option>
              </select>
            </div>
            <div class="setting-item">
              <label>最大令牌数: {{ generateForm.generation_params.max_tokens }}</label>
              <input type="range" v-model="generateForm.generation_params.max_tokens" min="100" max="2000" step="100">
            </div>
            <div class="setting-item">
              <label>创造性: {{ generateForm.generation_params.temperature }}</label>
              <input type="range" v-model="generateForm.generation_params.temperature" min="0" max="1" step="0.1">
            </div>
          </div>
        </div>

        <!-- 输入框 -->
        <div class="input-container">
          <button @click="showSettings = !showSettings" class="settings-btn" :class="{ active: showSettings }">
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <circle cx="12" cy="12" r="3"/>
              <path d="M12 1v6m0 6v6m11-7h-6m-6 0H1"/>
            </svg>
          </button>
          
          <form @submit.prevent="generateText" class="input-form">
            <div class="input-wrapper">
              <textarea 
                v-model="generateForm.prompt"
                placeholder="输入你的问题或需求..."
                rows="1"
                ref="textInput"
                @keydown="handleKeyDown"
                @input="adjustTextareaHeight"
                class="text-input"
                :disabled="generating"
              ></textarea>
              <button type="submit" :disabled="!generateForm.prompt.trim() || generating" class="send-btn">
                <svg v-if="!generating" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                  <line x1="22" y1="2" x2="11" y2="13"/>
                  <polygon points="22,2 15,22 11,13 2,9 22,2"/>
                </svg>
                <div v-else class="loading-spinner"></div>
              </button>
            </div>
            <div class="input-footer">
              <span class="char-count">{{ generateForm.prompt.length }}/2000</span>
              <span class="input-hint">按 Enter 发送，Shift + Enter 换行</span>
            </div>
          </form>
        </div>
      </div>
    </main>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed, watch, nextTick } from 'vue'
import { generate, records, getContentTypes, getPromptTemplate } from '@/api/text'

export default {
  name: 'Text',
  setup() {
    // 侧边栏相关状态
    const sidebarCollapsed = ref(false)
    const currentRecordId = ref(null)
    const selectedModule = ref('creative')
    
    // 响应式数据
    const loading = ref(false)
    const generating = ref(false)
    const generatedResult = ref(null)
    const recordList = ref([])
    const currentPage = ref(1)
    const totalPages = ref(1)
    const pageSize = 10
    const contentTypeOptions = ref([])
    const currentRecord = ref(null)
    
    // 新增功能相关
    const searchQuery = ref('')
    const sortOrder = ref('desc')
    const showScrollToBottom = ref(false)
    const conversationContent = ref(null)
    const showSettings = ref(false)
    const textInput = ref(null)
    const chatArea = ref(null)
    const messagesContainer = ref(null)
    
    // 计算属性
    const isModuleOnline = computed(() => {
      return true
    })
    
    const currentRecordTitle = computed(() => {
      if (currentRecordId.value) {
        const record = recordList.value.find(r => r.id === currentRecordId.value)
        return record ? `${getModuleText(record.module)} - ${getContentTypeText(record.content_type)}` : '新文本'
      }
      return '新文本'
    })
    
    const displayedRecords = computed(() => {
      let filtered = recordList.value
      
      if (searchQuery.value) {
        const query = searchQuery.value.toLowerCase()
        filtered = filtered.filter(record => 
          (record.prompt && record.prompt.toLowerCase().includes(query)) ||
          (getModuleText(record.module) && getModuleText(record.module).toLowerCase().includes(query)) ||
          (getContentTypeText(record.content_type) && getContentTypeText(record.content_type).toLowerCase().includes(query))
        )
      }
      
      return [...filtered].sort((a, b) => {
        const dateA = new Date(a.created_at)
        const dateB = new Date(b.created_at)
        return sortOrder.value === 'desc' ? dateB - dateA : dateA - dateB
      })
    })
    
    // 生成表单
    const generateForm = reactive({
      module: 'creative',
      content_type: '',
      language_style: 'casual',
      prompt: '',
      generation_params: {
        max_tokens: 1000,
        temperature: 0.7
      }
    })
    
    // 方法
    const toggleSidebar = () => {
      sidebarCollapsed.value = !sidebarCollapsed.value
    }
    
    const createNewChat = () => {
      currentRecordId.value = null
      currentRecord.value = null
      generatedResult.value = null
      clearForm()
      // 重新加载记录列表以确保最新状态
      loadRecords()
    }
    
    const loadRecord = async (recordId) => {
      currentRecordId.value = recordId
      const record = recordList.value.find(r => r.id === recordId)
      if (record) {
        generateForm.module = record.module
        generateForm.content_type = record.content_type
        generateForm.language_style = record.language_style
        generateForm.prompt = record.prompt
        // 不需要重新加载模块选项
        // onModuleChange()
      }
      
      try {
        const result = await records.getDetail(recordId)
        if (result.code === 200) {
          currentRecord.value = result.data
          await nextTick()
          scrollToBottom()
        }
      } catch (error) {
        console.error('获取记录详情失败:', error)
        // 如果API调用失败，使用列表中的记录
        if (record) {
          currentRecord.value = record
        }
      }
    }
    
    const onModuleChange = async () => {
      generateForm.module = selectedModule.value
      try {
        const result = await getContentTypes(generateForm.module)
        
        if (result.code === 200) {
          contentTypeOptions.value = result.data.content_types
          if (contentTypeOptions.value.length > 0) {
            generateForm.content_type = contentTypeOptions.value[0].value
            await onContentTypeChange()
          } else {
            generateForm.content_type = ''
            generateForm.prompt = ''
          }
        } else {
          contentTypeOptions.value = []
          generateForm.content_type = ''
          generateForm.prompt = ''
        }
      } catch (error) {
        console.error('获取内容类型列表失败:', error)
        contentTypeOptions.value = []
        generateForm.content_type = ''
        generateForm.prompt = ''
      }
    }
    
    const onContentTypeChange = async () => {
      if (generateForm.content_type) {
        try {
          const result = await getPromptTemplate(generateForm.content_type, generateForm.language_style)
          
          if (result.code === 200) {
            generateForm.prompt = result.data.template || ''
          } else {
            generateForm.prompt = ''
          }
        } catch (error) {
          console.error('获取提示词模板失败:', error)
          generateForm.prompt = ''
        }
      } else {
        generateForm.prompt = ''
      }
    }
    
    const onLanguageStyleChange = async () => {
      if (generateForm.content_type) {
        await onContentTypeChange()
      }
    }
    
    const generateText = async () => {
      if (!generateForm.prompt.trim()) {
        alert('请输入提示词')
        return
      }
      
      if (generateForm.prompt.length > 2000) {
        alert('提示词长度不能超过2000字符')
        return
      }
      
      try {
        generating.value = true
        currentRecord.value = null
        console.log('开始调用文本生成API:', generateForm)
        const result = await generate.create({
          module: generateForm.module,
          content_type: generateForm.content_type,
          language_style: generateForm.language_style,
          prompt: generateForm.prompt,
          generation_params: generateForm.generation_params
        })
        console.log('文本生成API响应:', result)
        
        if (result.code === 200) {
          generatedResult.value = result.data
          // 保存到记录中
          await saveToRecords()
          // 设置当前记录为新生成的记录
          currentRecordId.value = result.data.id
          currentRecord.value = {
            id: result.data.id,
            module: generateForm.module,
            content_type: generateForm.content_type,
            language_style: generateForm.language_style,
            prompt: generateForm.prompt,
            generated_content: result.data.generated_content,
            created_at: result.data.created_at || new Date().toISOString()
          }
          // 清空生成结果，触发显示历史记录
          setTimeout(() => {
            generatedResult.value = null
          }, 100)
          await nextTick()
          scrollToBottom()
        } else {
          alert('生成失败：' + result.msg)
        }
      } catch (error) {
        console.error('生成错误:', error)
        alert('生成失败，请稍后重试')
      } finally {
        generating.value = false
      }
    }
    
    const clearResult = () => {
      generatedResult.value = null
    }
    
    const clearForm = () => {
      generateForm.content_type = ''
      generateForm.language_style = 'casual'
      generateForm.prompt = ''
      generateForm.generation_params.max_tokens = 1000
      generateForm.generation_params.temperature = 0.7
      generatedResult.value = null
    }
    
    const saveToRecords = async () => {
      if (generatedResult.value) {
        // 检查记录是否已存在于列表中
        const existingIndex = recordList.value.findIndex(r => r.id === generatedResult.value.id)
        if (existingIndex === -1) {
          // 如果不存在，则添加到记录列表的开头
          recordList.value.unshift({
            id: generatedResult.value.id,
            module: generateForm.module,
            content_type: generateForm.content_type,
            language_style: generateForm.language_style,
            prompt: generateForm.prompt,
            generated_content: generatedResult.value.generated_content,
            created_at: generatedResult.value.created_at || new Date().toISOString(),
            is_favorite: false
          })
        } else {
          // 如果已存在，则更新记录
          recordList.value[existingIndex] = {
            ...recordList.value[existingIndex],
            module: generateForm.module,
            content_type: generateForm.content_type,
            language_style: generateForm.language_style,
            prompt: generateForm.prompt,
            generated_content: generatedResult.value.generated_content,
            created_at: generatedResult.value.created_at || new Date().toISOString()
          }
        }
        console.log('文本已保存到记录中')
      }
    }
    
    const loadRecords = async () => {
      try {
        loading.value = true
        console.log('开始加载文本记录列表，参数:', {
          page: currentPage.value,
          page_size: pageSize
        })
        const result = await records.getList({
          page: currentPage.value,
          page_size: pageSize
        })
        console.log('文本记录列表API响应:', result)
        
        if (result.code === 200) {
          // 确保记录按时间倒序排列（最新的在前面）
          const records = result.data.records || []
          records.sort((a, b) => new Date(b.created_at) - new Date(a.created_at))
          recordList.value = records
          totalPages.value = Math.ceil(result.data.total_count / pageSize)
        }
      } catch (error) {
        console.error('加载失败:', error)
      } finally {
        loading.value = false
      }
    }
    
    const refreshRecords = () => {
      loadRecords()
    }
    
    const viewRecord = async (record) => {
      try {
        console.log('查看记录详情，ID:', record.id)
        const result = await records.getDetail(record.id)
        console.log('记录详情API响应:', result)
        if (result.code === 200) {
          alert(`提示词: ${result.data.prompt}\n\n生成内容:\n${result.data.generated_content}`)
        }
      } catch (error) {
        alert('查看记录详情失败')
      }
    }
    
    const toggleFavorite = async (record) => {
      try {
        console.log('切换收藏状态，ID:', record.id)
        const result = await records.toggleFavorite(record.id)
        console.log('切换收藏状态API响应:', result)
        if (result.code === 200) {
          record.is_favorite = result.data.is_favorite
          const index = recordList.value.findIndex(r => r.id === record.id)
          if (index !== -1) {
            recordList.value[index].is_favorite = result.data.is_favorite
          }
        }
      } catch (error) {
        alert('切换收藏状态失败')
      }
    }
    
    const deleteRecord = async (recordId) => {
      if (!confirm('确定要删除这条记录吗？')) return
      
      try {
        console.log('删除记录，ID:', recordId)
        const result = await records.delete(recordId)
        console.log('删除记录API响应:', result)
        if (result.code === 200) {
          alert('删除成功')
          loadRecords()
          if (currentRecordId.value === recordId) {
            currentRecordId.value = null
            currentRecord.value = null
          }
        } else {
          alert('删除失败：' + result.msg)
        }
      } catch (error) {
        alert('删除失败')
      }
    }
    
    const changePage = (page) => {
      currentPage.value = page
      loadRecords()
    }
    
    const truncateText = (text, maxLength) => {
      if (!text) return ''
      return text.length > maxLength ? text.slice(0, maxLength) + '...' : text
    }
    
    const getModuleText = (module) => {
      const moduleMap = {
        'creative': '智能写作',
        'academic': '学术写作辅助'
      }
      return moduleMap[module] || module
    }
    
    const getContentTypeText = (contentType) => {
      const contentTypeMap = {
        'novel': '小说',
        'poetry': '诗歌',
        'script': '剧本',
        'story': '故事',
        'copy': '文案',
        'paper': '论文',
        'summary': '摘要',
        'reference': '参考文献',
        'report': '研究报告'
      }
      return contentTypeMap[contentType] || contentType
    }
    
    const formatDate = (dateString) => {
      const date = new Date(dateString)
      return date.toLocaleString('zh-CN')
    }
    
    const filterRecords = () => {
      // 过滤逻辑在computed属性中实现
    }
    
    const toggleSortOrder = () => {
      sortOrder.value = sortOrder.value === 'desc' ? 'asc' : 'desc'
    }
    
    const scrollToBottom = () => {
      if (conversationContent.value) {
        conversationContent.value.scrollTop = conversationContent.value.scrollHeight
      }
    }
    
    const copyResult = () => {
      let content = ''
      if (generatedResult.value) {
        content = generatedResult.value.generated_content
      } else if (currentRecord.value) {
        content = currentRecord.value.generated_content
      }
      
      if (content) {
        navigator.clipboard.writeText(content).then(() => {
          alert('内容已复制到剪贴板')
        }).catch(err => {
          console.error('复制失败:', err)
          alert('复制失败')
        })
      }
    }
    
    const insertTemplate = () => {
      const templates = [
        "请写一篇关于{主题}的{类型}，要求{要求}",
        "请以{风格}的语调写一篇{类型}，主题是{主题}",
        "请创作一个{类型}，内容包含{要点1}、{要点2}和{要点3}"
      ]
      
      const template = templates[Math.floor(Math.random() * templates.length)]
      generateForm.prompt = template
    }
    
    const copyText = async (text) => {
      try {
        await navigator.clipboard.writeText(text)
      } catch (err) {
        console.error('复制失败:', err)
      }
    }
    
    const formatRelativeTime = (dateString) => {
      const date = new Date(dateString)
      const now = new Date()
      const diff = now - date
      
      const minutes = Math.floor(diff / 60000)
      const hours = Math.floor(diff / 3600000)
      const days = Math.floor(diff / 86600000)
      
      if (minutes < 1) return '刚刚'
      if (minutes < 60) return `${minutes}分钟前`
      if (hours < 24) return `${hours}小时前`
      if (days < 7) return `${days}天前`
      return formatDate(dateString)
    }
    
    const handleKeyDown = (event) => {
      if (event.key === 'Enter' && !event.shiftKey) {
        event.preventDefault()
        if (generateForm.prompt.trim() && !generating.value) {
          generateText()
        }
      }
    }
    
    const adjustTextareaHeight = () => {
      const textarea = textInput.value
      if (textarea) {
        textarea.style.height = 'auto'
        textarea.style.height = Math.min(textarea.scrollHeight, 120) + 'px'
      }
    }
    
    const handleScroll = () => {
      if (conversationContent.value) {
        const { scrollTop, scrollHeight, clientHeight } = conversationContent.value
        showScrollToBottom.value = scrollHeight - scrollTop - clientHeight > 100
      }
    }
    
    onMounted(() => {
      loadRecords()
      onModuleChange()
      
      if (conversationContent.value) {
        conversationContent.value.addEventListener('scroll', handleScroll)
      }
    })
    
    watch(recordList, () => {
      nextTick(() => {
        scrollToBottom()
      })
    })
    
    return {
      sidebarCollapsed,
      currentRecordId,
      selectedModule,
      loading,
      generating,
      generatedResult,
      recordList,
      currentPage,
      totalPages,
      generateForm,
      contentTypeOptions,
      isModuleOnline,
      currentRecordTitle,
      currentRecord,
      toggleSidebar,
      createNewChat,
      loadRecord,
      generateText,
      clearResult,
      clearForm,
      saveToRecords,
      loadRecords,
      refreshRecords,
      viewRecord,
      toggleFavorite,
      deleteRecord,
      changePage,
      truncateText,
      getModuleText,
      getContentTypeText,
      formatDate,
      onModuleChange,
      onContentTypeChange,
      onLanguageStyleChange,
      searchQuery,
      sortOrder,
      displayedRecords,
      showScrollToBottom,
      conversationContent,
      showSettings,
      textInput,
      chatArea,
      messagesContainer,
      filterRecords,
      toggleSortOrder,
      scrollToBottom,
      copyResult,
      insertTemplate,
      copyText,
      formatRelativeTime,
      handleKeyDown,
      adjustTextareaHeight
    }
  }
}
</script>

<style scoped>
.ai-chat-container {
  display: flex;
  height: 100vh;
  background: linear-gradient(135deg, #FAF8F5 0%, #f5f3f0 50%, #F0EDE8 100%);
  position: relative;
}

.ai-chat-container::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-image: 
    radial-gradient(circle at 25% 25%, rgba(250, 234, 218, 0.1) 0%, transparent 25%),
    radial-gradient(circle at 75% 75%, rgba(163, 196, 188, 0.1) 0%, transparent 25%);
  background-size: 60px 60px;
  pointer-events: none;
  z-index: 0;
}

/* 侧边栏样式 */
.sidebar {
  width: 300px;
  background: rgba(255, 255, 255, 0.95);
  border-right: 1px solid #A3C4BC;
  display: flex;
  flex-direction: column;
  transition: width 0.3s ease;
  backdrop-filter: blur(20px);
  box-shadow: 2px 0 16px rgba(0, 0, 0, 0.05);
  z-index: 1;
}

.sidebar.collapsed {
  width: 60px;
}

.sidebar-header {
  padding: 16px;
  border-bottom: 1px solid rgba(163, 196, 188, 0.3);
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: linear-gradient(135deg, rgba(139, 115, 85, 0.05), rgba(163, 196, 188, 0.05));
}

.sidebar-toggle {
  background: none;
  border: none;
  cursor: pointer;
  color: #6b7280;
  padding: 4px;
  border-radius: 4px;
  transition: background 0.2s ease;
}

.sidebar-toggle:hover {
  background: rgba(163, 196, 188, 0.1);
}

.sidebar-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #8B7355;
}

.sidebar-content {
  padding: 16px;
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.new-chat-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 16px;
  background: linear-gradient(135deg, #8B7355 0%, #A3826B 100%);
  color: white;
  border: none;
  border-radius: 12px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 12px rgba(139, 115, 85, 0.3);
}

.new-chat-btn:hover {
  background: linear-gradient(135deg, #A3826B 0%, #8B7355 100%);
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(139, 115, 85, 0.4);
}

.module-selector {
  margin-bottom: 16px;
}

.module-select {
  width: 100%;
  padding: 10px 12px;
  border: 1px solid #A3C4BC;
  border-radius: 8px;
  background: rgba(255, 255, 255, 0.9);
  color: #8B7355;
  font-weight: 500;
  transition: all 0.3s ease;
}

.module-select:focus {
  outline: none;
  border-color: #8B7355;
  box-shadow: 0 0 0 3px rgba(139, 115, 85, 0.1);
}

.search-container {
  position: relative;
  margin-bottom: 16px;
}

.search-icon {
  position: absolute;
  left: 12px;
  top: 50%;
  transform: translateY(-50%);
  color: #9ca3af;
}

.search-input {
  width: 100%;
  padding: 10px 12px 10px 36px;
  border: 1px solid #A3C4BC;
  border-radius: 8px;
  background: rgba(255, 255, 255, 0.9);
  color: #374151;
  transition: all 0.3s ease;
}

.search-input:focus {
  outline: none;
  border-color: #8B7355;
  box-shadow: 0 0 0 3px rgba(139, 115, 85, 0.1);
}

.chat-history {
  flex: 1;
  overflow: hidden;
}

.history-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
}

.history-title {
  font-size: 14px;
  font-weight: 500;
  color: #6b7280;
  margin: 0;
}

.sort-btn {
  background: none;
  border: none;
  cursor: pointer;
  color: #6b7280;
  padding: 4px;
  border-radius: 4px;
  transition: background 0.2s ease;
}

.sort-btn:hover {
  background: rgba(163, 196, 188, 0.1);
}

.history-list {
  max-height: 100%;
  overflow-y: auto;
}

.history-item {
  display: flex;
  align-items: center;
  padding: 12px;
  border-radius: 8px;
  cursor: pointer;
  margin-bottom: 4px;
  transition: all 0.2s ease;
}

.history-item:hover {
  background: rgba(163, 196, 188, 0.1);
  transform: translateX(4px);
}

.history-item.active {
  background: rgba(163, 196, 188, 0.15);
  border-left: 3px solid #8B7355;
  border-radius: 0 8px 8px 0;
}

.history-content {
  flex: 1;
  min-width: 0;
}

.history-item .history-title {
  font-size: 14px;
  font-weight: 500;
  color: #1f2937;
  margin-bottom: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.history-time {
  font-size: 11px;
  color: #9ca3af;
}

.history-actions {
  display: flex;
  gap: 4px;
  opacity: 0;
  transition: opacity 0.2s ease;
}

.history-item:hover .history-actions {
  opacity: 1;
}

.action-btn {
  background: none;
  border: none;
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
  color: #6b7280;
  transition: all 0.2s ease;
}

.action-btn:hover {
  background: rgba(163, 196, 188, 0.1);
  color: #8B7355;
}

.action-btn.favorited {
  color: #f59e0b;
}

.delete-btn:hover {
  color: #ef4444;
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
  color: #9ca3af;
}

.empty-state svg {
  color: #A3C4BC;
  margin-bottom: 12px;
}

.empty-state p {
  margin: 0;
  font-size: 14px;
}

/* 主内容区域样式 */
.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: rgba(255, 255, 255, 0.6);
  backdrop-filter: blur(10px);
  z-index: 1;
}

.chat-area {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.welcome-screen {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px;
}

.welcome-content {
  text-align: center;
  max-width: 500px;
}

.ai-avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  background: linear-gradient(135deg, rgba(163, 196, 188, 0.2), rgba(139, 115, 85, 0.1));
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto 24px;
  border: 2px solid rgba(163, 196, 188, 0.3);
  backdrop-filter: blur(10px);
}

.welcome-title {
  font-size: 28px;
  font-weight: 600;
  color: #8B7355;
  margin: 0 0 8px 0;
}

.welcome-subtitle {
  font-size: 16px;
  color: #6b7280;
  margin: 0 0 32px 0;
}

.feature-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
  gap: 16px;
  margin-top: 32px;
}

.feature-card {
  padding: 16px;
  background: rgba(255, 255, 255, 0.9);
  border: 1px solid rgba(163, 196, 188, 0.2);
  border-radius: 12px;
  text-align: center;
  backdrop-filter: blur(10px);
  transition: all 0.3s ease;
}

.feature-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(139, 115, 85, 0.1);
  border-color: #8B7355;
}

.feature-card svg {
  color: #8B7355;
  margin-bottom: 8px;
}

.feature-card span {
  font-size: 14px;
  color: #374151;
  font-weight: 500;
}

/* 消息容器样式 */
.messages-container {
  flex: 1;
  overflow-y: auto;
  padding: 24px;
}

.message-group {
  margin-bottom: 32px;
}

.message {
  display: flex;
  gap: 12px;
  margin-bottom: 16px;
  max-width: 800px;
}

.user-message {
  flex-direction: row-reverse;
  margin-left: auto;
}

.message-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.user-avatar {
  background: linear-gradient(135deg, #8B7355, #A3826B);
  color: white;
  font-size: 14px;
  border: 2px solid rgba(255, 255, 255, 0.8);
  box-shadow: 0 2px 8px rgba(139, 115, 85, 0.3);
}

.ai-avatar {
  background: linear-gradient(135deg, rgba(163, 196, 188, 0.2), rgba(139, 115, 85, 0.1));
  font-size: 14px;
  border: 2px solid rgba(163, 196, 188, 0.3);
  backdrop-filter: blur(10px);
}

.message-content {
  flex: 1;
  min-width: 0;
}

.user-message .message-content {
  text-align: right;
}

.message-text {
  background: rgba(249, 250, 251, 0.9);
  padding: 16px 20px;
  border-radius: 18px;
  font-size: 15px;
  line-height: 1.6;
  color: #374151;
  border: 1px solid rgba(163, 196, 188, 0.2);
  backdrop-filter: blur(10px);
  white-space: pre-wrap;
  word-break: break-word;
}

.user-message .message-text {
  background: linear-gradient(135deg, #8B7355, #A3826B);
  color: white;
  border: none;
  box-shadow: 0 2px 8px rgba(139, 115, 85, 0.3);
}

.message-time {
  font-size: 12px;
  color: #9ca3af;
  margin-top: 8px;
}

.message-actions {
  margin-top: 12px;
  display: flex;
  gap: 8px;
  opacity: 0;
  transition: opacity 0.2s ease;
}

.message:hover .message-actions {
  opacity: 1;
}

.message-actions .action-btn {
  padding: 6px 12px;
  background: rgba(255, 255, 255, 0.9);
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  font-size: 12px;
  color: #374151;
  cursor: pointer;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  gap: 4px;
  backdrop-filter: blur(10px);
}

.message-actions .action-btn:hover {
  background: #f3f4f6;
  border-color: #d1d5db;
  color: #8B7355;
}

/* 生成中状态 */
.message.generating {
  opacity: 0.8;
}

.typing-indicator {
  display: flex;
  gap: 4px;
  align-items: center;
  padding: 16px 20px;
}

.typing-indicator span {
  width: 8px;
  height: 8px;
  background: #A3C4BC;
  border-radius: 50%;
  animation: typing 1.4s infinite ease-in-out;
}

.typing-indicator span:nth-child(2) {
  animation-delay: 0.2s;
}

.typing-indicator span:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes typing {
  0%, 60%, 100% {
    transform: translateY(0);
  }
  30% {
    transform: translateY(-10px);
  }
}

/* 输入区域样式 */
.input-area {
  padding: 24px;
  border-top: 1px solid rgba(163, 196, 188, 0.3);
  background: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(20px);
}

.settings-panel {
  max-height: 0;
  overflow: hidden;
  transition: max-height 0.3s ease;
  margin-bottom: 16px;
}

.settings-panel.expanded {
  max-height: 200px;
}

.settings-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
  padding: 20px;
  background: rgba(255, 255, 255, 0.9);
  border: 1px solid rgba(163, 196, 188, 0.3);
  border-radius: 12px;
  backdrop-filter: blur(10px);
}

.setting-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.setting-item label {
  font-size: 12px;
  font-weight: 500;
  color: #374151;
}

.setting-item select,
.setting-item input[type="range"] {
  padding: 8px 12px;
  border: 1px solid #A3C4BC;
  border-radius: 8px;
  background: rgba(255, 255, 255, 0.9);
  color: #374151;
  font-size: 14px;
  transition: all 0.3s ease;
}

.setting-item select:focus,
.setting-item input[type="range"]:focus {
  outline: none;
  border-color: #8B7355;
  box-shadow: 0 0 0 3px rgba(139, 115, 85, 0.1);
}

.setting-item input[type="range"] {
  padding: 0;
  border: none;
  background: linear-gradient(to right, #8B7355, #A3C4BC);
  height: 4px;
  border-radius: 2px;
  appearance: none;
}

.setting-item input[type="range"]::-webkit-slider-thumb {
  appearance: none;
  width: 16px;
  height: 16px;
  border-radius: 50%;
  background: #8B7355;
  cursor: pointer;
  border: 2px solid white;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.setting-item input[type="range"]::-moz-range-thumb {
  width: 16px;
  height: 16px;
  border-radius: 50%;
  background: #8B7355;
  cursor: pointer;
  border: 2px solid white;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.input-container {
  max-width: 800px;
  margin: 0 auto;
}

.input-wrapper {
  display: flex;
  gap: 12px;
  align-items: flex-end;
  margin-bottom: 8px;
}

.settings-btn {
  background: none;
  border: none;
  cursor: pointer;
  padding: 12px;
  border-radius: 8px;
  color: #6b7280;
  transition: all 0.3s ease;
  flex-shrink: 0;
}

.settings-btn:hover,
.settings-btn.active {
  background: rgba(163, 196, 188, 0.1);
  color: #8B7355;
}

.input-form {
  flex: 1;
}

.text-input {
  width: 100%;
  padding: 14px 16px;
  border: 1px solid #A3C4BC;
  border-radius: 12px;
  font-size: 15px;
  line-height: 1.5;
  resize: none;
  min-height: 48px;
  max-height: 200px;
  outline: none;
  transition: all 0.3s ease;
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
  color: #374151;
}

.text-input:focus {
  border-color: #8B7355;
  box-shadow: 0 0 0 3px rgba(139, 115, 85, 0.1);
  background: rgba(255, 255, 255, 0.95);
}

.text-input:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.send-btn {
  padding: 14px 16px;
  background: linear-gradient(135deg, #8B7355, #A3826B);
  color: white;
  border: none;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 50px;
  height: 48px;
  box-shadow: 0 2px 8px rgba(139, 115, 85, 0.3);
}

.send-btn:hover:not(:disabled) {
  background: linear-gradient(135deg, #A3826B, #8B7355);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(139, 115, 85, 0.4);
}

.send-btn:disabled {
  background: #A3C4BC;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.loading-spinner {
  width: 20px;
  height: 20px;
  border: 2px solid transparent;
  border-top: 2px solid white;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.input-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: #9ca3af;
}

.char-count {
  font-weight: 500;
}

.input-hint {
  display: flex;
  align-items: center;
  gap: 4px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .sidebar {
    position: fixed;
    left: 0;
    top: 0;
    height: 100vh;
    z-index: 1000;
    transform: translateX(-100%);
    transition: transform 0.3s ease;
  }

  .sidebar.collapsed {
    width: 300px;
    transform: translateX(-100%);
  }

  .main-content {
    width: 100%;
  }

  .settings-grid {
    grid-template-columns: 1fr;
  }

  .input-wrapper {
    flex-direction: column;
    gap: 8px;
  }

  .send-btn {
    width: 100%;
  }

  .message {
    max-width: 100%;
  }

  .feature-grid {
    grid-template-columns: 1fr;
  }
}
</style>